package logic

import (
	"context"
	"errors"
	"manuscript-service/models/mysql"

	"manuscript-service/manrpc/internal/svc"
	"manuscript-service/manrpc/manrpc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type ManAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManAddLogic {
	return &ManAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManAddLogic) ManAdd(in *manrpc.ManAddRequest) (*manrpc.ManAddResponse, error) {
	// todo: add your logic here and delete this line
	begin := mysql.DB.Begin()
	var man mysql.Manuscript
	if err := man.ManFind(mysql.DB, in.Title); err == nil {
		begin.Rollback()
		return nil, errors.New("稿件标题已存在")
	}
	cates := mysql.Category{
		Model:    gorm.Model{},
		CateName: in.CateName,
	}
	if err := cates.FindName(mysql.DB, in.CateName); err != nil {
		begin.Rollback()
		return nil, err
	}
	mans := mysql.Manuscript{
		Model:   gorm.Model{},
		Title:   in.Title,
		Like:    in.Like,
		Content: in.Content,
		Info:    in.Info,
		CateId:  int64(cates.ID),
	}
	if err := mans.ManAdd(mysql.DB); err != nil {
		begin.Rollback()
		return nil, err
	}
	begin.Commit()
	return &manrpc.ManAddResponse{
		ManuscriptsId: int64(mans.ID),
	}, nil
}
